<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools show-before>
        <template #before>
          <span>当前有{{ page.total }}条数据</span>
        </template>
        <template #after>
          <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <el-table border :data="list">
        <el-table-column label="序号" sortable="" type="index" />
        <el-table-column label="姓名" sortable="" prop="username" />
        <el-table-column label="头像" sortable="" width="120px">
          <template v-slot="{row:{staffPhoto}}">
            <img
              v-imgerror="require('@/assets/common/head.jpg')"
              :src="staffPhoto"
              style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
              @click="showStaffPhoto(staffPhoto)"
            />

          </template>
        </el-table-column>
        <el-table-column label="工号" sortable="" prop="workNumber" />
        <el-table-column label="聘用形式" sortable="" prop="formOfEmployment">
          <!-- 方法1通过过滤器格式化 -->
          <template v-slot="{row}">
            {{ row.formOfEmployment | formOfEmployment }}
          </template>
        </el-table-column>
        <!-- 方法2 -->
        <!-- <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatFormOfEmployment">
        </el-table-column> -->
        <el-table-column label="部门" sortable="" prop="departmentName" />
        <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
          <template v-slot="{row}">
            {{ row.timeOfEntry|formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" sortable="" prop="enableState">
          <template v-slot="{row}">
            <el-switch
              :value="row.enableState===1"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" fixed="right" width="280">
          <template v-slot="{row}">
            <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="center" align="middle" style="height:60px">
        <el-pagination
          layout="prev, pager, next"
          :total="50"
          :page-size="page.size"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-row>
    </div>
    <el-dialog title="头像" :visible.sync="showCodeDialog" width="30%">
      <canvas ref="canvas"></canvas>
    </el-dialog>
    <add-employee :show-dialog.sync="showDialog"></add-employee>
    <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId"></assign-role>
  </div>
</template>

<script>
import AddEmployee from './components/add-employee.vue'
import employeesEnum from '@/api/constant/employees.js'
import { delEmployee, getEmployeeList } from '@/api/employees'
import { pick } from 'lodash'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
var QRCode = require('qrcode')
// import { actions } from 'plop-templates/view/prompt'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  filters: {
    formOfEmployment(val) {
      const f = employeesEnum.hireType.find(t => t.id === val)
      return f ? f.value : '未知'
    }
  },
  props: {},
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 2,
        total: 0
      },
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  mounted() {},
  methods: {
    async  editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailByid(id)
      this.showRoleDialog = true
    },
    showStaffPhoto(url) {
      this.showCodeDialog = true
      this.$nextTick(() => {
        const canvas = this.$refs.canvas
        QRCode.toCanvas(canvas, url, function(error) {
          if (error) console.error(error)
          console.log(error)
        })
      })
    },
    exportData() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const values = Object.values(headers)
        const results = rows.map(o => {
          const t = pick(o, values)
          t.timeOfEntry = formatDate(t.timeOfEntry)
          t.correctionTime = formatDate(t.correctionTime)
          const f = employeesEnum.hireType.find(m => m.id === t.formOfEmployment)
          t.formOfEmployment = f ? f.value : '未知'
          return Object.values(t)
        })
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          multiHeader,
          merges,
          header: Object.keys(headers),
          data: results,
          filename: '工作表'
        })
      })
    },
    delEmployee(id) {
      // 确认 通过elemecon
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async action => {
        // 发请求
        await delEmployee(id)
        this.$message({
          message: '操作成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        // 刷新页面
        this.getEmployeeList()
      }).catch(() => {

      })
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
    }
    // formatFormOfEmployment(row,column,val,index){
    // const f=employessEnum.hireType.find(t=>t.id===val)
    // return f?f.value:'未知
    // }，
    //
    //
  }
}
</script>

<style lang="scss" scoped>

</style>
